<?php
declare (strict_types = 1);

namespace command\model;

use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\facade\Config;

class ModelUpdate extends Command
{

    protected function configure()
    {
        // 指令配置
        $this->setName('model:update')
            ->addArgument('module', Argument::OPTIONAL, "app module name")
            ->addOption('tables', null, Option::VALUE_REQUIRED, 'op tables list')
            ->setDescription('auto update model');        
    }

    protected function execute(Input $input, Output $output)
    {
        $module = $input->getArgument('module');
        $modulePath = $module?$module."/":'';

        $db = $this->app->db;

        if ($input->hasOption('tables')) {
            $tables = $input->getOption('tables');
            $list = explode(',',$tables);
        } else {
        	$list = $db->getTables();
        }
        
        $prefix = Config::get('database.connections.mysql.prefix')??'';

        $path = $this->app->getBasePath().$modulePath."model";

        if (!is_dir($path)) {
            $output->writeln('path is not exist');
            return;
        }
        

        foreach ($list as $key => $value) {
            
            $name = str_replace("_","",ucwords(str_replace($prefix,'',$value),"_"));

            $fields = $db->getFields($value);
            
            $fieldInfo = $this->parseField($fields);

            $pathName = $path . DIRECTORY_SEPARATOR . $name .".php";

            if(!is_file($pathName))continue;//文件不存在跳过

            $stub = file_get_contents($pathName);

            file_put_contents(
                $path . DIRECTORY_SEPARATOR . $name .".php",
                preg_replace(
                    ['/(?<=protected \$schema = )[\s\S]*?(?=;)/','/(?<=protected \$pk = )[\s\S]*?(?=;)/'],
                    [$fieldInfo['schema'],"'".$fieldInfo['pk']."'"],
                    $stub
                )
            );

        }

    	// 指令输出
    	$output->writeln('model');
    }

    /**
     * 格式化数据表字段
     *
     * @param array $fieldArr
     * @return void
     */
    private function parseField($fieldArr)
    {
        $schema = '['.PHP_EOL;
        $pk = "";
        foreach ($fieldArr as $key => $value) {
            $schema.='        "'.$value['name'].'"=>"'.$value['type'].'",'.PHP_EOL;
            if($value['primary']&&!$pk){
                $pk = $value['name'];
            }
        }

        $schema = trim($schema,',')."    ]";

        return ['pk'=>$pk,'schema'=>$schema];
    }
}
